<?php

namespace App\Admin\Controllers;

use App\Models\AdminUser;
use App\Models\Department;
use App\Models\DepartmentData;
use App\Models\Role;
use App\Models\User;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Http\Auth\Permission;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Http\Repositories\Administrator;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Models\Administrator as AdministratorModel;
use Dcat\Admin\Show;
use Dcat\Admin\Support\Helper;
use Dcat\Admin\Widgets\Tree;
use Illuminate\Http\Request;

class UserController extends AdminController
{
    public function index(Content $content)
    {
        Admin::style(controllerIndexStyle(130));
        return $content->translation($this->translation())->body($this->grid());
    }

    protected function grid()
    {
        $admin_user = AdminUser::find(Admin::user()->id);
        $builder = AdminUser::query()->with(['roles']);
        if (!$admin_user->isAdministrator()) {
            $builder->whereHas('roles', function($q) {
                $q->where('slug', Role::ROLE_SLUG_MANGER);
            });
        }
        return Grid::make($builder, function (Grid $grid) use ($admin_user) {
            $grid->column('gid', '账号');
            $grid->column('name');
            $grid->column('phone');
            $grid->column('dwmc');
            $grid->column('ddb_dwmc')->sortable();

            if ($admin_user->isAdministrator()) {
                $grid->column('roles')->pluck('name')->label('primary', 3);

                $permissionModel = config('admin.database.permissions_model');
                $roleModel = config('admin.database.roles_model');
                $nodes = (new $permissionModel())->allNodes();
                $grid->column('permissions')
                    ->if(function () {
                        return ! $this->roles->isEmpty();
                    })
                    ->showTreeInDialog(function (Grid\Displayers\DialogTree $tree) use (&$nodes, $roleModel) {
                        $tree->nodes($nodes);

                        foreach (array_column($this->roles->toArray(), 'slug') as $slug) {
                            if ($roleModel::isAdministrator($slug)) {
                                $tree->checkAll();
                            }
                        }
                    })
                    ->else()
                    ->display('');
            }

            $grid->quickSearch(['id', 'name', 'zjhm', 'gid']);

            $grid->showColumnSelector(false);

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableView();
                if ($actions->getKey() == AdministratorModel::DEFAULT_ID) {
                    $actions->disableDelete();
                }
                $actions->disableEdit();
                $actions->disableQuickEdit(false);
            });

            $grid->disableCreateButton();
            $created_url = admin_route('auth.users.create');
            $grid->tools(view('admin.grid._grid_title', ['title' => '管理员']));
            Form::dialog('添加管理员')->click('.node-create-form')->options(['forceRefresh' => true])->width('800px')->height('700px')->success('Dcat.reload()')->resetButton(false);
            $grid->tools('<span class="pull-right"><a href="javascript:void(0)" data-url="'.$created_url.'" class="node-create-form btn btn-primary"><i class="feather icon-plus"></i> 新增</a></span>');
        });
    }

    protected function detail($id)
    {
        return Show::make($id, Administrator::with(['roles']), function (Show $show) {
            $show->field('id');
            $show->field('username');
            $show->field('name');

            $show->field('avatar', __('admin.avatar'))->image();

            if (config('admin.permission.enable')) {
                $show->field('roles')->as(function ($roles) {
                    if (! $roles) {
                        return;
                    }

                    return collect($roles)->pluck('name');
                })->label();

                $show->field('permissions')->unescape()->as(function () {
                    $roles = $this->roles->toArray();

                    $permissionModel = config('admin.database.permissions_model');
                    $roleModel = config('admin.database.roles_model');
                    $permissionModel = new $permissionModel();
                    $nodes = $permissionModel->allNodes();

                    $tree = Tree::make($nodes);

                    $isAdministrator = false;
                    foreach (array_column($roles, 'slug') as $slug) {
                        if ($roleModel::isAdministrator($slug)) {
                            $tree->checkAll();
                            $isAdministrator = true;
                        }
                    }

                    if (! $isAdministrator) {
                        $keyName = $permissionModel->getKeyName();
                        $tree->check(
                            $roleModel::getPermissionId(array_column($roles, $keyName))->flatten()
                        );
                    }

                    return $tree->render();
                });
            }

            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    public function form()
    {
        return Form::make(Administrator::with(['roles']), function (Form $form) {
            $admin_user = AdminUser::find(Admin::user()->id);
            if ($form->isEditing()) {
                $form->display('gid', '账号');
            } else {
                $form->text('gid', '账号')->prepend('')->required()
                ->creationRules(['required', "unique:admin_users"]);
            }
            $form->text('name', '姓名')->prepend('')->required();
            $form->text('phone', '手机号')->prepend('')->required();

            if ($admin_user->isAdministrator()) {
                $form->multipleSelect('roles', '角色')
                    ->options(function () {
                        return Role::all()->pluck('name', 'id');
                    })
                    ->customFormat(function ($v) {
                        return array_column($v, 'id');
                    });
            } else {
                $role = Role::where('slug', Role::ROLE_SLUG_MANGER)->first();
                $form->multipleSelect('roles', '角色')->options([$role->id => $role->name])->default([$role->id]);
            }

            $form->select('dwdm', '班子单位')->options(Department::query()->where('type', 1)->pluck('dwmc', 'dwdm'));
            $form->hidden('dwmc');
            $form->select('ddb_dwdm', '党委单位')->options(Department::query()->where('type', 2)->pluck('dwmc', 'dwdm'));
            $form->hidden('ddb_dwmc');
            if ($form->getKey()) {
                $form->checkbox('change_password', ' ')->options([1 => '修改密码'])
                    ->when(1, function($form) {
                        $form->password('password', trans('admin.password'))
                            ->minLength(5)
                            ->maxLength(20)
                            ->customFormat(function ($paths) {
                                return '';
                            });
                    });
            } else {
                $form->password('password', trans('admin.password'))
                    ->required()
                    ->minLength(5)
                    ->maxLength(20);
            }
            $form->saving(function(Form $form) {
                $inputs = request()->all();
                $chanage_password = isset($inputs['change_password']) && collect($inputs['change_password'])->filter()->all() ? 1 : 0;
                if ($chanage_password && $form->password) {
                    $form->password = bcrypt($form->password);
                } else {
                    $form->deleteInput('password');
                }
                $form->deleteInput('change_password');

                if ($inputs['dwdm']) {
                    $form->dwmc = Department::query()->where('dwdm', $inputs['dwdm'])->value('dwmc');
                } else {
                    $form->dwdm = '';
                    $form->dwmc = '';
                }

                if ($inputs['ddb_dwdm']) {
                    $form->ddb_dwmc = Department::query()->where('dwdm', $inputs['ddb_dwdm'])->value('dwmc');
                } else {
                    $form->ddb_dwdm = '';
                    $form->ddb_dwmc = '';
                }
            });
        });
    }

    public function destroy($id)
    {
        if (in_array(AdministratorModel::DEFAULT_ID, Helper::array($id))) {
            Permission::error();
        }

        return parent::destroy($id);
    }

    public function ajaxUsers(Request $request)
    {
        if ($request->has('t') && $request->get('t') == 'all') {
            $q = $request->get('query');
            $result = User::query()->where('name', 'like', "%$q%")->orWhere('zjhm', 'like', "%$q%")->orWhere('phone', 'like', "%$q%")->limit(30)->select('name', 'gid', 'phone', 'zjhm')->get();
            return response()->json($result->toArray());
        }
        $q = $request->get('q');
        return User::where('name', 'like', "%$q%")->paginate(null, ['gid', 'name as text']);
    }
}
